<template>
  <el-dialog 
    :model-value="visible" 
    @update:model-value="handleVisibleChange"
    :title="isEdit ? '编辑单元' : '新增单元'" 
    width="700px" 
    :before-close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" @submit.prevent>
      <!-- 基本信息 -->
      <el-divider content-position="left">基本信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="单元名称" prop="unitName">
            <el-input v-model="formData.unitName" placeholder="请输入单元名称" maxlength="50" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单元编号" prop="unitNo">
            <el-input v-model="formData.unitNo" placeholder="请输入单元编号" maxlength="20" show-word-limit disabled/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="单元编码" prop="unitCode">
            <el-input v-model="formData.unitCode" placeholder="请输入单元编码" maxlength="50" show-word-limit disabled/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属社区" prop="communityName">
            <el-input v-model="formData.communityName" placeholder="所属社区" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属楼栋" prop="buildingId">
            <el-select v-model="formData.buildingId" placeholder="请选择楼栋" style="width: 100%" @change="handleBuildingChange">
              <el-option 
                v-for="item in buildingOptions" 
                :key="item.id" 
                :label="item.buildingName" 
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 建筑信息 -->
      <el-divider content-position="left">建筑信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="楼层数" prop="floorCount">
            <el-input-number v-model="formData.floorCount" :min="1" :max="100" placeholder="楼层数" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="房间数" prop="roomCount">
            <el-input-number v-model="formData.roomCount" :min="0" :max="1000" placeholder="房间数" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="户数" prop="householdCount">
            <el-input-number v-model="formData.householdCount" :min="0" :max="500" placeholder="户数" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="单元面积" prop="area">
            <el-input-number v-model="formData.area" :min="0" :max="10000" :precision="2" placeholder="平方米" style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="管理员" prop="managerName">
            <el-input v-model="formData.managerName" placeholder="请输入管理员姓名" maxlength="50" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 设施配置 -->
      <el-divider content-position="left">设施配置</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="电梯配置" prop="hasElevator">
            <el-radio-group v-model="formData.hasElevator">
                          <el-radio :value="1">有电梯</el-radio>
            <el-radio :value="0">无电梯</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="电梯数量" prop="elevatorCount" v-if="formData.hasElevator === 1">
            <el-input-number v-model="formData.elevatorCount" :min="1" :max="10" placeholder="电梯数量" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="门禁类型" prop="doorAccessType">
            <el-select v-model="formData.doorAccessType" placeholder="请选择门禁类型" style="width: 100%">
              <el-option label="密码" :value="1" />
              <el-option label="刷卡" :value="2" />
              <el-option label="人脸识别" :value="3" />
              <el-option label="指纹" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="门禁密码" prop="accessCode" v-if="formData.doorAccessType === 1">
            <el-input v-model="formData.accessCode" placeholder="请输入门禁密码" maxlength="20" show-password />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="配套设施" prop="facilities">
        <el-input v-model="formData.facilities" type="textarea" placeholder="请输入配套设施信息（JSON格式）" :rows="3" maxlength="500" show-word-limit />
      </el-form-item>

      <!-- 状态信息 -->
      <el-divider content-position="left">状态信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
                          <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="排序" prop="sortOrder">
            <el-input-number v-model="formData.sortOrder" :min="0" :max="999" placeholder="排序值" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注信息" :rows="3" maxlength="500" show-word-limit />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">{{ isEdit ? '更新' : '创建' }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { unitApi } from '@/api/unit'
import { buildingApi } from '@/api/building'
import { communityApi } from '@/api/community'

const props = defineProps({
  visible: Boolean,
  formData: Object
})
const emit = defineEmits(['update:visible', 'success'])

const formRef = ref()
const loading = ref(false)
const isEdit = ref(false)
const buildingOptions = ref<any[]>([])
const communityOptions = ref<any[]>([])

const formData = ref({
  unitName: '',
  // unitNo: '',
  // unitCode: '',
  buildingId: undefined as number | undefined,
  communityId: undefined as number | undefined,
  communityName: '',
  floorCount: 1,
  roomCount: 0,
  householdCount: 0,
  area: undefined as number | undefined,
  managerName: '',
  hasElevator: 0,
  elevatorCount: 0,
  doorAccessType: 1,
  accessCode: '',
  facilities: '',
  status: 1,
  sortOrder: 0,
  remark: ''
})

const formRules = {
  unitName: [
    { required: true, message: '请输入单元名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度2-50个字符', trigger: 'blur' }
  ],
  unitNo: [
    { required: true, message: '请输入单元编号', trigger: 'blur' },
    { min: 1, max: 20, message: '长度1-20个字符', trigger: 'blur' }
  ],
  unitCode: [
    { required: true, message: '请输入单元编码', trigger: 'blur' },
    { min: 1, max: 50, message: '长度1-50个字符', trigger: 'blur' }
  ],
  buildingId: [
    { required: true, message: '请选择所属楼栋', trigger: 'change' }
  ],
  floorCount: [
    { required: true, message: '请输入楼层数', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '楼层数1-100', trigger: 'blur' }
  ],
  roomCount: [
    { type: 'number', min: 0, max: 1000, message: '房间数0-1000', trigger: 'blur' }
  ],
  householdCount: [
    { type: 'number', min: 0, max: 500, message: '户数0-500', trigger: 'blur' }
  ],
  area: [
    { type: 'number', min: 0, max: 10000, message: '面积0-10000平方米', trigger: 'blur' }
  ],
  hasElevator: [
    { required: true, message: '请选择电梯配置', trigger: 'change' }
  ],
  elevatorCount: [
    { type: 'number', min: 1, max: 10, message: '电梯数量1-10', trigger: 'blur' }
  ],
  doorAccessType: [
    { required: true, message: '请选择门禁类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  sortOrder: [
    { type: 'number', min: 0, max: 999, message: '排序值0-999', trigger: 'blur' }
  ]
}

const handleVisibleChange = (value: boolean) => {
  emit('update:visible', value)
}

const handleClose = () => {
  emit('update:visible', false)
}

const handleBuildingChange = async (buildingId: number) => {
  if (buildingId) {
    try {
      // 根据楼栋ID获取楼栋信息，包括社区信息
      const buildingRes = await buildingApi.getBuildingDetail(buildingId)
      if (buildingRes.data) {
        const building = buildingRes.data
        formData.value.communityId = building.communityId
        formData.value.communityName = building.communityName || ''
      }
    } catch (error) {
      console.error('获取楼栋信息失败:', error)
    }
  } else {
    formData.value.communityId = undefined
    formData.value.communityName = ''
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true
    
    // 准备提交数据
    const submitData = {
      ...formData.value,
      // 确保数值字段正确
      floorCount: Number(formData.value.floorCount),
      roomCount: Number(formData.value.roomCount || 0),
      householdCount: Number(formData.value.householdCount || 0),
      area: formData.value.area ? Number(formData.value.area) : undefined,
      elevatorCount: formData.value.hasElevator === 1 ? Number(formData.value.elevatorCount || 0) : 0,
      sortOrder: Number(formData.value.sortOrder || 0)
    }
    
    if (isEdit.value) {
      await unitApi.updateUnit(props.formData.id, submitData)
    } else {
      await unitApi.createUnit(submitData)
    }
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    emit('success')
    handleClose()
  } catch (e) {
    if (e !== false) ElMessage.error('操作失败')
  } finally {
    loading.value = false
  }
}

const loadBuildingOptions = async () => {
  try {
    const res = await buildingApi.getBuildingPage({
      current: 1,
      size: 1000
    })
    
    const buildingList = res.data?.records || res.data || []
    
    buildingOptions.value = buildingList.filter(item => 
      item && typeof item.id === 'number' && item.id > 0 && 
      item.buildingName && typeof item.buildingName === 'string'
    )
  } catch (e) {
    console.error('加载楼栋失败:', e)
    ElMessage.error('加载楼栋失败')
    buildingOptions.value = []
  }
}

// 重置表单
const resetForm = () => {
  formData.value = {
    unitName: '',
    unitNo: '',
    unitCode: '',
    buildingId: undefined,
    communityId: undefined,
    communityName: '',
    floorCount: 1,
    roomCount: 0,
    householdCount: 0,
    area: undefined,
    managerName: '',
    hasElevator: 0,
    elevatorCount: 0,
    doorAccessType: 1,
    accessCode: '',
    facilities: '',
    status: 1,
    sortOrder: 0,
    remark: ''
  }
  formRef.value?.clearValidate()
}

// 监听表单数据变化
watch(() => props.formData, (newData) => {
  if (newData) {
    formData.value = { ...newData }
    // 延迟清除验证错误，确保数据完全加载后再清除
    nextTick(() => {
      setTimeout(() => {
        formRef.value?.clearValidate()
      }, 100)
    })
  } else {
    resetForm()
  }
}, { immediate: true })

// 监听弹窗显示状态
watch(() => props.visible, (val) => {
  if (val) {
    isEdit.value = !!props.formData
    if (!props.formData) {
      resetForm()
    }
    loadBuildingOptions()
  }
}, { immediate: true })
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
}

.el-divider {
  margin: 20px 0 15px 0;
}

.el-divider__text {
  font-weight: 600;
  color: #409eff;
}
</style> 